from django.shortcuts import render, redirect
from rbac import models
from rbac.forms import RoleForm, MenuForm
from django.db.models import Q


# Create your views here.
def role_list(request):
    all_roles = models.Role.objects.all()

    return render(request, 'rbac/role_list.html', {'all_roles': all_roles})


def role_change(request, pk=None, *args, **kwargs):
    obj = models.Role.objects.filter(pk=pk).first()
    form_obj = RoleForm(instance=obj)

    if request.method == 'POST':
        form_obj = RoleForm(request.POST, instance=obj)
        if form_obj.is_valid():
            form_obj.save()

            return redirect('rbac:role_list')

    return render(request, 'form.html', {'form_obj': form_obj})


def menu_list(request):
    mid = request.GET.get('mid')

    all_menus = models.Menu.objects.all()

    if not mid:
        all_permissions = models.Permission.objects.all()
    else:
        all_permissions = models.Permission.objects.filter(Q(menu_id=mid) | Q(parent__menu_id=mid))

    all_permissions = all_permissions.values('id', 'title', 'url', 'name', 'menu_id', 'menu__title', 'parent_id')
    permissions = {}

    for i in all_permissions:
        menu_id = i['menu_id']
        id = i['id']
        if  menu_id:
            i['children'] = []
            permissions[id] = i

    print(permissions)
    for i in all_permissions:
        pid = i['parent_id']
        if pid:
            permissions[pid]['children'].append(i)

    return render(request, 'rbac/menu_list.html',
                  {'mid': mid, 'all_menus': all_menus, 'all_permissions': permissions.values()})


def menu_change(request, pk=None, *args, **kwargs):
    obj = models.Menu.objects.filter(pk=pk).first()
    form_obj = MenuForm(instance=obj)

    if request.method == 'POST':
        form_obj = MenuForm(request.POST, instance=obj)
        if form_obj.is_valid():
            form_obj.save()
            return redirect('rbac:menu_list')

    return render(request, 'meun_form.html', {'form_obj': form_obj})
